"""
Grave! Important! Важно!

Proletoj el ĉiuj landoj, unuiĝu!
Workers of the world, unite!
Пролетарии всех стран, соединяйтесь!

https://tkom.pro
"""

import os
import re
from django.utils.translation import gettext_lazy as _
from corsheaders.defaults import default_headers
import datetime
import environ

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

env = environ.Env(
    # set casting, default value
    DEBUG=(bool, False),
    EMAIL_USE_TLS=(bool, True),
    EMAIL_USE_SSL=(bool, True),
    ALLOWED_HOSTS=(list, ['localhost',]),
    EMAIL_PORT=(int, 587)
)
environ.Env.read_env(os.path.join(BASE_DIR, '.env'))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = env('SECRET_KEY')

# SECURITY WARNING: don't run with debug turned on in production!
# DEBUG = True
# DEBUG = False
DEBUG = env('DEBUG')

# New in Django Development version. 3.2
# Default primary key field type to use for models that don’t have a field with primary_key=True.
DEFAULT_AUTO_FIELD = 'django.db.models.AutoField'

# ALLOWED_HOSTS = env('ALLOWED_HOSTS')
ALLOWED_HOSTS = env.list('ALLOWED_HOSTS')

# Proxy protocol
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

# Use proxy header X_FORWARDED_HOST
USE_X_FORWARDED_HOST = True

# Max uploads fields
DATA_UPLOAD_MAX_NUMBER_FIELDS = 10000

# Application definition
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',
    'django.contrib.flatpages',
    'django.contrib.postgres',
    'django.contrib.gis',
    'django_celery_beat',
    'corsheaders',
    'django_hosts',
    'graphene_django',
    'captcha',
    'channels',
    'embed_video',
    "graphql_jwt.refresh_token.apps.RefreshTokenConfig",
    'akademio.apps.AkademioConfig',
    'dekretumoj.apps.DekretumojConfig',
    # 'dokumentoj.apps.DokumentojConfig',
    'enciklopedio.apps.EnciklopedioConfig',
    'enhavo.apps.EnhavoConfig',
    'esploradoj.apps.EsploradojConfig',
    'eventoj.apps.EventojConfig',
    'fotoj.apps.FotojConfig',
    'ideoj.apps.IdeojConfig',
    'informiloj.apps.InformilojConfig',
    'internacia_plano.apps.InternaciaPlanoConfig',
    'komunumoj.apps.KomunumojConfig',
    'kombatantoj.apps.KombatantojConfig',
    'konferencoj.apps.KonferencojConfig',
    'kodo.apps.KodoConfig',
    'lokalizo.apps.LokalizoConfig',
    'main.apps.MainConfig',
    'mesagxilo.apps.MesagxiloConfig',
    'memorkartoj.apps.MemorkartojConfig',
    'muroj.apps.MuroConfig',
    'novayoj.apps.NovayojConfig',
    'premioj.apps.PremiojConfig',
    'tamagocxi.apps.TamagocxiConfig',
    'registrado.apps.RegistradoConfig',
    'sano.apps.SanoConfig',
    'sontrakoj.apps.SontrakojConfig',
    'statistiko.apps.StatistikoConfig',
    'teknika_subteno.apps.TeknikaSubtenoConfig',
    'uzantoj.apps.UzantojConfig',
    'videoj.apps.VideojConfig',
    'versioj.apps.VersiojConfig',
    'geo.apps.GeoConfig',
    'enketo.apps.EnketoConfig',
    'laborspacoj.apps.LaborspacoConfig',
    'kanvasoj.apps.KanvasojConfig',
    # Universo apps
    'agado.apps.AgadoConfig',
    'profiloj.apps.ProfiloConfig',
    'universo_bazo.apps.UniversoBazoConfig',
    'dokumentoj.apps.DokumentojConfig',
    'kosmo.apps.KosmoConfig',
    'mono.apps.MonoConfig',
    'objektoj.apps.ObjektojConfig',
    'organizoj.apps.OrganizojConfig',
    'rajtoj.apps.RajtojConfig',
    'resursoj.apps.ResursojConfig',
    'sciigoj.apps.SciigojConfig',
    'scipovoj.apps.ScipovojConfig',
    'sxablonoj.apps.SxablonoConfig',
    'taskoj.apps.TaskojConfig',
    'projektoj.apps.ProjektojConfig',
    'universo_uzantoj_websocket.apps.UniversoUzantojWebsocketConfig',
    'oauth2_provider',
    'crispy_forms',
    'crispy_bootstrap4',
]

MIDDLEWARE = [
    'django.middleware.common.BrokenLinkEmailsMiddleware',
    'django_hosts.middleware.HostsRequestMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'siriuso.middleware.SiriusoUzantoTokenAuth',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'oauth2_provider.middleware.OAuth2TokenMiddleware',
    'siriuso.middleware.SiriusoUzantoLingvo',
    'django.middleware.locale.LocaleMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
    'django_hosts.middleware.HostsResponseMiddleware',
    'siriuso.middleware.SiriusoAutomataKunteksto',
    'siriuso.middleware.SiriusoPorteblaKliento',
    'siriuso.middleware.SiriusoUzantoHorzono'
]

TEMPLATE_CONTEXT_PROCESSORS = (
    "module.context_processors.site",
)

SITE_URL = env('SITE_URL')

# Graphene
GRAPHENE = {
    'SCHEMA': 'siriuso.api.schema.schema',
    "MIDDLEWARE": [
        "graphql_jwt.middleware.JSONWebTokenMiddleware",
    ],
}

GRAPHQL_JWT = {
    "JWT_VERIFY_EXPIRATION": True,
    "JWT_EXPIRATION_DELTA": datetime.timedelta(days=7),
    "JWT_AUTH_HEADER_PREFIX": 'JWT',
    "JWT_LONG_RUNNING_REFRESH_TOKEN": True,
    "JWT_REFRESH_EXPIRATION_DELTA": datetime.timedelta(days=10),
}
    # "JWT_AUTH_HEADER_PREFIX": 'ROBOTO',
    # "JWT_EXPIRATION_DELTA": datetime.timedelta(minutes=10),


# Channels
ASGI_APPLICATION = "siriuso.routing.application"
CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels_redis.core.RedisChannelLayer",
        "CONFIG": {
            "hosts": [("redis", 6379)],
        },
    },
}

# CORS: https://github.com/ottoyiu/django-cors-headers#configuration

# Разрешать все запросы
CORS_ORIGIN_ALLOW_ALL = env.bool('CORS_ORIGIN_ALLOW_ALL')

CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_WHITELIST = (
    'http://localhost:8080',
    'http://localhost:8000',
    'http://localhost:3000',
    'http://127.0.0.1:8080',
    'http://127.0.0.1:8000',
    'http://127.0.0.1:3000'
)

# Разрешенные заголовки
CORS_ALLOW_HEADERS = default_headers + (
    'x-auth-token',
    'x-client-tz',
    'x-client-lang',
    'x-content-lang',
)

ADMINS = (
    # ('pinballwizard', 'mentenebris@gmail.com'),
    ('Равиль Сарваритдинов', 'ra9oaj@osfk.ru'),
    ('admin-web', 'admin-web@tehnokom.su'),
    ('archive', 'arhiv@tehnokom.su'),
)

# MANAGERS = (
#    ('Владимир Левадный', 'miru-mir@tehnokom.su'),
# )


ROOT_URLCONF = 'siriuso.urls'

ROOT_HOSTCONF = 'siriuso.hosts'  # Change `mysite` to the name of your project

DEFAULT_HOST = 'www'  # Name of the default host, we will create it in the next steps

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'main.context_processors.siriuso_context',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'siriuso.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': env('DB_ENGINE'),
        # 'ENGINE': 'django.db.backends.postgresql_psycopg2', удалён в Django 3.0
        'HOST': env('DB_HOST'),
        'PORT': env('DB_PORT'),
        'NAME': env('DB_NAME'),
        'USER': env('DB_USER'),
        'PASSWORD': env('DB_PASSWORD'),
        'TEST': {
            'NAME': env('DB_TEST_NAME'),
        },
    },
    # 'osm': {
    #     'ENGINE': 'django.contrib.gis.db.backends.postgis',
    #     'HOST': 'osm',
    #     'PORT': '5432',
    #     'NAME': 'siriuso',
    #     'USER': 'siriuso',
    #     'PASSWORD': '12345',
    # },
}

# Redis Cache
CACHES = {
    'default': {
        'BACKEND': 'django_redis.cache.RedisCache',
        'LOCATION': 'redis://redis:6379/0',
        'TIMEOUT': 300,
        'OPTIONS': {
            'CLIENT_CLASS': 'django_redis.client.DefaultClient',
        }
    }
}

SESSION_ENGINE = "django.contrib.sessions.backends.cache"
SESSION_CACHE_ALIAS = "default"


# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

AUTHENTICATION_BACKENDS = [
    'oauth2_provider.backends.OAuth2Backend',
    # 'django.contrib.auth.backends.ModelBackend',
    'siriuso.backends.UzantoAuthBackend',
    'siriuso.backends.TokenAuthBackend',
    "graphql_jwt.backends.JSONWebTokenBackend",
]

OAUTH2_PROVIDER = {
#     'SCOPES': {
#         'read': 'Read scope',
#         'write': 'Write scope',
#     },

#     'CLIENT_ID_GENERATOR_CLASS': 'oauth2_provider.generators.ClientIdGenerator',

    'REQUEST_APPROVAL_PROMPT': 'auto',
}

# Internationalization

LANGUAGE_CODE = 'ru-ru'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

LANGUAGES = (
    ('eo-xx', _('Internacia (Esperanto)')),
    ('ru-ru', _('Rusa')),
    ('en-gb', _('Angla')),
    ('sr-rs', _('Serba')),
    ('et-ee', _('Estona')),
    ('lv-lv', _('Latva')),
    ('de-de', _('Germana'))
)

# SMTP settings
EMAIL_BACKEND = env('EMAIL_BACKEND')
EMAIL_USE_TLS = env('EMAIL_USE_TLS')
EMAIL_USE_SSL = env('EMAIL_USE_SSL')
EMAIL_HOST = env('EMAIL_HOST')
EMAIL_PORT = env('EMAIL_PORT')
EMAIL_HOST_USER = env('EMAIL_HOST_USER')
EMAIL_HOST_PASSWORD = env('EMAIL_HOST_PASSWORD')

# настройка ящиков
# SERVER_EMAIL = 'no-reply@tehnokom.su'
# DEFAULT_FROM_EMAIL = 'no-reply@tehnokom.su'
# EMAIL_NO_REPLY = 'no-reply@tehnokom.su'
SERVER_EMAIL = 'test-mailer@tmail.tehnokom.su'
DEFAULT_FROM_EMAIL = 'test-mailer@tmail.tehnokom.su'
EMAIL_NO_REPLY = 'test-mailer@tmail.tehnokom.su'

# https://docs.djangoproject.com/en/dev/ref/settings/#login-url
# LOGIN_URL = '/ensaluti/'
LOGIN_URL = 'login'
LOGIN_REDIRECT_URL = '/api/v1.1/'
LOGOUT_URL = 'logout'
LOGOUT_REDIRECT_URL = '/login'
CRISPY_TEMPLATE_PACK = 'bootstrap4'

# месторасположение файлов перевода
LOCALE_PATHS = (
    'locale',
)

# Django Sites Framework
SITE_ID = 1

STATIC_URL = env('STATIC_URL')
STATIC_ROOT = env('STATIC_ROOT')
MEDIA_URL = env('MEDIA_URL')
MEDIA_ROOT = env('MEDIA_ROOT')


AUTH_USER_MODEL = 'main.Uzanto'

# Embed video settings
# http://django-embed-video.readthedocs.io/en/v1.1.0/api/embed_video.settings.html
EMBED_VIDEO_BACKENDS = (
    'embed_video.backends.YoutubeBackend',
    # 'embed_video.backends.VimeoBackend',
    # 'embed_video.backends.SoundCloudBackend',
)


# Путь до БД GeoIP2 (https://dev.maxmind.com/geoip/geoip2/geolite2/)
GEOIP_PATH = '/opt/GeoIP/GeoLite2-City_20180206/GeoLite2-City.mmdb'

# RECAPTCHA MODULE SETTINGS
NOCAPTCHA = True
# Test keys
RECAPTCHA_PUBLIC_KEY = env('RECAPTCHA_PUBLIC_KEY')
RECAPTCHA_PRIVATE_KEY = env('RECAPTCHA_PRIVATE_KEY')
SILENCED_SYSTEM_CHECKS = env.list('SILENCED_SYSTEM_CHECKS')
SMARTCAPTCHA_SERVER_KEY = env('SMARTCAPTCHA_SERVER_KEY')

# CELERY SETTINGS
CELERY_BROKER_URL = 'amqp://siriuso:siriuso@rabbitmq:5672//'
CELERY_RESULT_BACKEND = 'redis://redis:6379/1'
CELERY_TASK_SERIALIZER = 'json'
CELERY_ACCEPT_CONTENT = ['json']
CELERY_TASK_ANNOTATIONS = {'tasks.add': {'rate_limit': '10/s'}}
# CELERY_broker_url = 'amqp://siriuso:siriuso@rabbitmq:5672//'
# CELERY_result_backend = 'redis://redis:6379/1'
# CELERY_task_serializer = 'json'
# CELERY_accept_content = ['json']
# CELERY_task_annotations = {'tasks.add': {'rate_limit': '10/s'}}

# Logging

# LOGGING = {
#     'version': 1,
#     'disable_existing_loggers': False,
#     'formatters': {
#         'verbose': {
#             'format': '%(levelname)s %(asctime)s %(module)s %(message)s'
#         },
#         'simple': {
#             'format': '%(levelname)s %(message)s'
#         },
#     },
#     'filters': {
#         'require_debug_true': {
#             '()': 'django.utils.log.RequireDebugTrue',
#         },
#         'require_debug_false': {
#             '()': 'django.utils.log.RequireDebugFalse',
#         },
#     },
#     'handlers': {
#         'file': {
#             'level': 'INFO',
#             'filters': ['require_debug_false'],
#             'class': 'logging.FileHandler',
#             'filename': '/var/log/django_debug.log',
#             'formatter': 'verbose'
#         },
#         'console': {
#             'level': 'INFO',
#             'filters': ['require_debug_true'],
#             'class': 'logging.StreamHandler',
#             'formatter': 'simple'
#         },
#         'mail_admins': {
#             'level': 'ERROR',
#             'filters': ['require_debug_false'],
#             'class': 'django.utils.log.AdminEmailHandler',
#             'include_html': True,
#         }
#     },
#     'loggers': {
#         'django': {
#             'handlers': ['file', 'console', 'mail_admins'],
#             'level': 'DEBUG',
#             'propagate': True,
#         },
#         # 'django.server': {
#         #     'handlers': ['mail_admins'],
#         #     'level': 'ERROR',
#         #     'propagate': True,
#         # },
#     },
# }
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
        },
    },
    'root': {
        'handlers': ['console'],
        'level': 'WARNING',
    },
    'loggers': {
        'django': {
            'handlers': ['console'],
            # 'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'),
            'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'),
            'propagate': False,
        },
    },
}


IGNORABLE_404_URLS = [
    re.compile(r'^/wp-content/'),
    re.compile(r'^/wp-admin/'),
    re.compile(r'^/im/'),
    re.compile(r'^/sockjs/'),
    re.compile(r'^/packages/'),
    re.compile(r'^/redmine/')
]


ODATA_USER = env('ODATA_USER')
ODATA_PASSWORD = env('ODATA_PASSWORD')
ODATA_URL = env('ODATA_URL')
